package com.pet.shop.controller.upload;

import com.pet.shop.utils.ApiResultUtil;
import com.pet.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/api/upload")
@RestController
public class ApiUploadController {

    private static final Logger logger = LoggerFactory.getLogger(ApiUploadController.class);

    @Value("${fileUploadPath}")
    private String fileUploadPath;
    @Value("${fileContextPath}")
    private String fileContextPath;
    @Value("${fileViewServer}")
    private String fileViewServer;


    /**
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/uploadFile")
    public Map<String, Object> fileUpload(HttpServletRequest request, HttpServletResponse response){
        logger.info("上传文件。。。。。");
        MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest)request;

        Map<String,MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if(StringUtils.isEmpty(fileUploadPath)){
            fileUploadPath = request.getSession().getServletContext().getRealPath("") + "/uploadFiles/";
        }
        //上传单个文件
        for(Map.Entry<String, MultipartFile> entity:fileMap.entrySet()){
            MultipartFile mf = entity.getValue();

            logger.debug("构建临时文件目录---->:" + fileUploadPath);
            File rootFile = new File(fileUploadPath);
            if(!rootFile.exists()){
                logger.debug("创建临时文件目录");
                rootFile.mkdirs();
            }
            try{
                //取一个新的名字
                String fileName = UUID.randomUUID().toString().replace("-", "") + FileUtils.getExtension(mf.getOriginalFilename());
                File uploadFile = new File(fileUploadPath + fileName);
                resultMap.put(mf.getOriginalFilename(), fileName);
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                resultMap.put("server", fileViewServer);
                resultMap.put("path", fileContextPath + fileName);
                logger.info("图片上传成功 {}" + fileContextPath + fileName);

                return ApiResultUtil.success(resultMap);
            }catch(Exception e){
                logger.error("上传文件失败", e);
            }
        }

        return ApiResultUtil.error_server("文件上传失败");
    }
}
